package com.example.dao;

import com.example.domain.Comment;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;
//评论的增删改查
@Repository
public interface CommentMapper {

    @Select("SELECT c.*, u.username FROM comment c LEFT JOIN user u ON c.user_id = u.id WHERE c.post_id = #{postId} AND c.status = 'active' ORDER BY c.create_time ASC")
    @Results(id = "commentMap", value = {
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "content", property = "content"),
            @Result(column = "user_id", property = "userId"),
            @Result(column = "post_id", property = "postId"),
            @Result(column = "parent_id", property = "parentId"),
            @Result(column = "create_time", property = "createTime"),
            @Result(column = "status", property = "status"),
            @Result(column = "username", property = "username")
    })
    List<Comment> findByPostId(@Param("postId") Integer postId);

    @Select("SELECT c.*, u.username FROM comment c LEFT JOIN user u ON c.user_id = u.id WHERE c.parent_id = #{parentId} AND c.status = 'active' ORDER BY c.create_time ASC")
    @ResultMap("commentMap")
    List<Comment> findByParentId(@Param("parentId") Integer parentId);
    //添加
    @Insert("INSERT INTO comment (content, user_id, post_id, parent_id, status, create_time) VALUES (#{content}, #{userId}, #{postId}, #{parentId}, #{status}, #{createTime})")
    void save(Comment comment);
    //修改
    @Update("UPDATE comment SET content = #{content}, update_time = CURRENT_TIMESTAMP WHERE id = #{id}")
    void update(Comment comment);

    @Update("UPDATE comment SET status = #{status} WHERE id = #{id}")
    void updateStatus(@Param("id") Integer id, @Param("status") String status);
    //查询
    @Select("SELECT c.*, u.username FROM comment c LEFT JOIN user u ON c.user_id = u.id WHERE c.id = #{id}")
    @ResultMap("commentMap")
    Comment findById(@Param("id") Integer id);

    @Select("SELECT c.*, u.username FROM comment c LEFT JOIN user u ON c.user_id = u.id WHERE c.status = 'active' ORDER BY c.create_time DESC")
    @ResultMap("commentMap")
    List<Comment> findAll();
    //删除
    @Delete("DELETE FROM comment WHERE id = #{id}")
    void delete(@Param("id") Integer id);

    @Select("SELECT c.*, u.username FROM comment c LEFT JOIN user u ON c.user_id = u.id WHERE c.user_id = #{userId} AND c.status = 'active' ORDER BY c.create_time DESC")
    @ResultMap("commentMap")
    List<Comment> findByUserId(@Param("userId") Integer userId);

    @Select("SELECT c.*, u.username FROM comment c LEFT JOIN user u ON c.user_id = u.id ORDER BY c.create_time DESC")
    @ResultMap("commentMap")
    List<Comment> findAllForAdmin();

    @Select("SELECT COUNT(*) FROM comment WHERE post_id = #{postId} AND status = 'active'")
    int getCommentCountByPostId(@Param("postId") Integer postId);
}